# views.py
import requests
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import AllowAny
from rest_framework_simplejwt.tokens import RefreshToken

from backend import settings
from .models import User
from rest_framework.parsers import MultiPartParser
import uuid
import os

class WeChatLoginView(APIView):
    permission_classes = [AllowAny]

    def post(self, request):
        code = request.data.get('code')
        avatar_url = request.data.get('avatar_url')
        username = request.data.get('username')

        if not code:
            return Response({'error': '缺少 code'}, status=400)

        wx_url = "https://api.weixin.qq.com/sns/jscode2session"
        params = {
            'appid': 'wxc2804f074e86a4b6',
            'secret': '0f46e37bffcf35f37db5f8d0b1e70c72',
            'js_code': code,
            'grant_type': 'authorization_code'
        }
        resp = requests.get(wx_url, params=params)
        data = resp.json()

        openid = data.get('openid')
        if not openid:
            return Response({'error': '微信验证失败'}, status=400)

        user, created = User.objects.get_or_create(openid=openid)

        # 更新头像和用户名（不覆盖已有）
        if avatar_url:
            user.avatar_url = avatar_url
        if username:
            user.username = username
        user.save()

        refresh = RefreshToken.for_user(user)
        return Response({
            'refresh': str(refresh),
            'access': str(refresh.access_token),
            'username': user.username,
            'avatar_url': user.avatar_url,
            'id': user.id
        })



class AvatarUploadView(APIView):
    parser_classes = [MultiPartParser]
    permission_classes = [AllowAny]

    def post(self, request):
        avatar = request.FILES.get('avatar')
        if not avatar:
            return Response({'error': '未上传头像'}, status=400)

        # 重命名文件避免冲突
        ext = os.path.splitext(avatar.name)[1]
        filename = f"{uuid.uuid4().hex}{ext}"
        avatar.name = filename

        # 保存到 media/avatar/
        from django.core.files.storage import default_storage
        avatar_path = default_storage.save(f"avatar/{filename}", avatar)

        avatar_url = f"{request.build_absolute_uri('/')[:-1]}{settings.MEDIA_URL}{avatar_path}"
        return Response({'avatar_url': avatar_url})

    # 'appid': 'wxc2804f074e86a4b6',
    #     'secret': '0f46e37bffcf35f37db5f8d0b1e70c72',